package topofstack.networkserverutils.fragments;

import java.util.ArrayList;
import java.util.List;

import topofstack.networkserverutils.R;
import topofstack.networkserverutils.adapter.EmailServerAdapter;
import topofstack.networkserverutils.net.Nslookup;
import topofstack.networkserverutils.util.Constants;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class EmailServer extends ListFragment{
	
	public List<String> servers;
	
	private Button submit;
	private EditText urlField;
	private TextView heading;
	private ListView listView;
	private EmailServerAdapter adapter;
	
	private ProgressDialog dialog;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		servers = new ArrayList<String>();
		adapter = new EmailServerAdapter(getActivity());
		setListAdapter(getAdapter());
		
		View convertView = inflater.inflate(R.layout.email_server, container, false);
		listView = (ListView) convertView.findViewById(android.R.id.list);
		urlField = (EditText) convertView.findViewById(R.id.email_server_url);
		heading = (TextView) convertView.findViewById(R.id.email_server_heading);
		submit = (Button) convertView.findViewById(R.id.email_server_submit);
		submit.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				String url = urlField.getText().toString().trim();
				if(url.length() == 0)
					Toast.makeText(getActivity(), Constants.ERROR_EMPTY_FIELD,
							Toast.LENGTH_SHORT).show();
				else {
					new RetriveData().execute(new Void[0]);
					
					dialog = new ProgressDialog(getActivity());
					dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					dialog.setMessage(Constants.DIALOG_MESSAGE);
					dialog.setIndeterminate(true);
					dialog.show();
				}
			}
		});
		
		return convertView;
	}
	
	public EmailServerAdapter getAdapter() {
		return adapter;
	}

	private class RetriveData extends AsyncTask<Void, Void, Void> {
		
		String url;
		
		@Override
		protected Void doInBackground(Void... params) {
			
			url = urlField.getText().toString();
			servers = Nslookup.getMX(url);
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void v) {
			if(servers == null)
				Toast.makeText(getActivity(), Constants.ERROR_MESSAGE, Toast.LENGTH_SHORT)
					.show();
			else {
				getAdapter().update(servers);
				heading.setText("MX Records: " + url);
				heading.setBackgroundResource(android.R.color.darker_gray);
			}
			
			dialog.cancel();
		}
	}
}
